package www.wen.com.common.lib.view.popuview

import android.content.Context
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import www.wen.com.common.lib.data.entities.ItemIsSelected
import www.wen.com.common.lib.helper.ResultUiCallBack

/**
 * @author WEN
 * @Description: 如果需要设置默认选中效果列表的就继承这个
 * @date 2021/4/25 21:35
 */
abstract class BaseBottomSelectListPopupView<T : ItemIsSelected>(
        context: Context,
        data: List<T>,
        private var resultCallBack: ResultUiCallBack<T>? = null,
        private var repeatCallBack: ResultUiCallBack<T>? = null,
) : BaseBottomListPopupView<T>(context, data),
        OnItemClickListener {

    private var mCurrentPosition: Int = 0

    override fun onCreate() {
        super.onCreate()
        data.forEachIndexed { index, data ->
            if (data.isSelected) {
                mCurrentPosition = index
                return@forEachIndexed
            }
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if (mCurrentPosition != position) {

            val currentEntity = (adapter.getItem(position)) as ItemIsSelected
            currentEntity.isSelected = true

            val oldEntity = (adapter.getItem(mCurrentPosition)) as ItemIsSelected
            oldEntity.isSelected = false

            adapter.notifyItemChanged(position)
            adapter.notifyItemChanged(mCurrentPosition)

            mCurrentPosition = position
            resultCallBack?.invoke(view,adapter.data[position] as T,this@BaseBottomSelectListPopupView)
        } else {
            repeatClick(adapter, view, position)
        }
    }

    /**
     * 重复点击同一个时的事件
     */
    open fun repeatClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        repeatCallBack?.invoke(view,adapter.data[position] as T,this@BaseBottomSelectListPopupView)
    }


}